import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Vector;

public class ScheduleThread extends Thread {

	private final int maxTickInterval = 59 * 1000; // ms
	private final byte MAX_DEVICE_NR = 64;

	private int tickInterval = 1000; // ms
	private static String className = "ScheduleThread: ";
	private Vector<ScheduledEvent> scheduledEvents;
	private Vector<Device> devices;
	
	private int lastSize = 0;


	public ScheduleThread(Vector<ScheduledEvent> scheduledEvents,
			Vector<Device> devices) {
		// load settings
		this.tickInterval = Math.min(GeneralSettings.scheduleTickInterval,
				maxTickInterval); // ms

		this.scheduledEvents = scheduledEvents;
		this.devices = devices;
	}
	
	public void setScheduledEvents(Vector<ScheduledEvent> scheduledEvents) {
		DEBUG("setScheduledEvents: " + scheduledEvents.size());
		
		this.scheduledEvents = scheduledEvents;
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(tickInterval);
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			
			if (scheduledEvents.size() > 0) {

				int maxDiff = tickInterval * 2; // ms
				Iterator<ScheduledEvent> i = scheduledEvents.iterator();
				int scheduledEventCounter = 0;

				while (i.hasNext()) {
					scheduledEventCounter++;

					Calendar now = Calendar.getInstance();
					ScheduledEvent scheduledEvent = i.next();
					Calendar then = scheduledEvent.getStartTime();

					if(scheduledEvents.size() != lastSize) {
						DateFormat dateFormat = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						DEBUG("Event "
								+ scheduledEventCounter
								+ ": "
								+ dateFormat.format(then.getTime())
								+ " "
								+ Macros.getDeviceString(scheduledEvent
										.getDeviceIDs()) + " On: "
								+ scheduledEvent.getSwitchOn());
					}

					long timeDiff = Math.abs(then.getTimeInMillis()
							- now.getTimeInMillis());

					if (timeDiff <= maxDiff) {

						for (byte j = 1; j <= MAX_DEVICE_NR; j++) {
							
							if (Macros.getDevice(j,
									scheduledEvent.getDeviceIDs())
									&& scheduledEvent.getSwitchOn()) {
								TellstickInterface.turnOnDevice(j,
										Macros.getDeviceName(devices, j));
							} else if (Macros.getDevice(j,
									scheduledEvent.getDeviceIDs())) {
								TellstickInterface.turnOffDevice(j,
										Macros.getDeviceName(devices, j));
							}
						}
						
						i.remove();
					}
				}
				
				lastSize = scheduledEvents.size();
			}
		}
	}

	private static void DEBUG(String debugString) {
		Macros.DEBUG(className + debugString);
	}
}
